﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace parking_program
{
    public partial class register_form : Form
    {
        public register_form()
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
        }

        private void back_login_button_Click(object sender, EventArgs e)
        {
            login_form login_Form = new login_form();
            login_Form.Show();
            this.Close();
        }

        private void register_button_Click(object sender, EventArgs e)
        {
            // 读取文本框内容
            string userIdText = id_textbox.Text;
            string username = user_textbox.Text;
            string password = password_textbox.Text;
            string car1Num = car1_num_textbox.Text;
            string car2Num = car2_num_textbox.Text;
            string carType1 = car_type1.Text;
            string carType2 = car_type2.Text;
            string car1Color = car1_color.Text;
            string car2Color = car2_color.Text;

            // 创建数据库配置读取器
            MySqlConfigReaderClass configReader = new MySqlConfigReaderClass("D:\\Cshell-out\\parking\\config.txt");
            MySqlBaseInfoClass baseInfo = configReader.MySqlBaseInfo;

            // 创建查询和插入类实例
            MySqlQueryClass queryClass = new MySqlQueryClass(baseInfo.ServerIp, baseInfo.DatabaseUsername, baseInfo.DatabasePassword, baseInfo.DatabaseName);
            MySqlInsertClass insertClass = new MySqlInsertClass(baseInfo.ServerIp, baseInfo.DatabaseUsername, baseInfo.DatabasePassword, baseInfo.DatabaseName);

            // 检查User表中是否已存在相同的用户名
            DataTable userCheckTable = queryClass.QueryData(
                "SELECT * FROM User WHERE username = @username",
                new MySqlParameter("@username", username)
            );
            if (userCheckTable.Rows.Count > 0)
            {
                MessageBox.Show("用户名已存在！");
                return;
            }

            // 生成唯一的user_id
            int userId = GenerateUserId(queryClass);
            if (userId == 0)
            {
                MessageBox.Show("无法生成唯一的用户ID。");
                return;
            }

            // 插入User表
            int userIdFromDb = insertClass.InsertData(
                "INSERT INTO User (user_id, username, password) VALUES (@userId, @username, @password)",
                new MySqlParameter("@userId", userId),
                new MySqlParameter("@username", username),
                new MySqlParameter("@password", password)
            );

            // 生成vehicle_id
            int vehicleId1 = GenerateVehicleId(queryClass);
            int vehicleId2 = -1;
            if (!string.IsNullOrEmpty(car2Num) && !string.IsNullOrEmpty(carType2) && !string.IsNullOrEmpty(car2Color))
            {
                vehicleId2 = GenerateVehicleId(queryClass);
            }

            // 插入Vehicle表
            insertClass.InsertData(
                "INSERT INTO Vehicle (vehicle_id, vehicle_plate, vehicle_model, color, user_id) VALUES (@vehicleId, @car1Num, @carType1, @car1Color, @userId)",
                new MySqlParameter("@vehicleId", vehicleId1),
                new MySqlParameter("@car1Num", car1Num),
                new MySqlParameter("@carType1", carType1),
                new MySqlParameter("@car1Color", car1Color),
                new MySqlParameter("@userId", userIdFromDb) // 使用从数据库返回的userIdFromDb
            );

            if (vehicleId2 != -1)
            {
                insertClass.InsertData(
                    "INSERT INTO Vehicle (vehicle_id, vehicle_plate, vehicle_model, color, user_id) VALUES (@vehicleId, @car2Num, @carType2, @car2Color, @userId)",
                    new MySqlParameter("@vehicleId", vehicleId2),
                    new MySqlParameter("@car2Num", car2Num),
                    new MySqlParameter("@carType2", carType2),
                    new MySqlParameter("@car2Color", car2Color),
                    new MySqlParameter("@userId", userIdFromDb) // 使用从数据库返回的userIdFromDb
                );
            }

            MessageBox.Show("注册成功！");
        }

        private int GenerateUserId(MySqlQueryClass queryClass)
        {
            int userId;
            do
            {
                userId = new Random().Next(1, int.MaxValue);
            } while (queryClass.QueryData(
                "SELECT * FROM User WHERE user_id = @userId",
                new MySqlParameter("@userId", userId)
            ).Rows.Count > 0);

            return userId;
        }

        private int GenerateVehicleId(MySqlQueryClass queryClass)
        {
            DataTable vehicleCountTable = queryClass.QueryData("SELECT COUNT(*) FROM Vehicle");
            int vehicleCount = vehicleCountTable.Rows.Count > 0 ? Convert.ToInt32(vehicleCountTable.Rows[0]["COUNT(*)"]) : 0;

            if (vehicleCount == 0)
            {
                // 如果Vehicle表为空，则生成1-200之间的随机数
                return new Random().Next(1, 201);
            }
            else
            {
                // 如果Vehicle表不为空，则生成与其他vehicle_id不同的1-200之间的随机数
                HashSet<int> existingVehicleIds = new HashSet<int>();
                DataTable vehicleIdTable = queryClass.QueryData("SELECT vehicle_id FROM Vehicle");
                foreach (DataRow row in vehicleIdTable.Rows)
                {
                    existingVehicleIds.Add(Convert.ToInt32(row["vehicle_id"]));
                }
                int vehicleId;
                do
                {
                    vehicleId = new Random().Next(1, 201);
                } while (existingVehicleIds.Contains(vehicleId));
                return vehicleId;
            }
        }

        private void reset_button_Click(object sender, EventArgs e)
        {
            id_textbox.Text = null;
            user_textbox.Text = null;
            password_textbox.Text = null;
            password_confirm_textbox.Text = null;
            car1_num_textbox.Text = null;
            car2_num_textbox.Text = null;
            car_type1.Text = null;
            car_type2.Text = null;
            car1_color.Text = null;
            car2_color.Text = null;
        }

        private void report_link_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            report_form report_Form = new report_form();
            report_Form.Show();
            this.Close();
        }
    }
}